<html>

<head>

</head>

<body>
<?php

include ("app/config.php");
include ("app/lib/functions.php");

$testtype = isset($_GET["testtype"]) ? $_GET["testtype"] : "";

switch ($testtype) {

	case "createuserform":
?>
	<form action="test.php?testtype=createuser" method="post" target="targetframe">
		<p> User: <input type="text" name="user" /> </p>
		<p> Password: <input type="password" name="password" /> </p>
		<p> Retype: <input type="password" name="password2" /> </p>
		<input type="submit" value="Create" />
		<input type="reset" value="Reset" />
	</form>
	<iframe id="targetframe" name="targetframe" src="test.php" height="200" width="400" frameborder="1"></iframe>
<?php
		;
	break;

	case "createuser":
		
	// error array to validate errors
		$errorsArray = array();
		
	// variables to use in creating new user
		$user = ""; // TODO change for $login and change also other related code
		$password = "";
		
	// validation of user and password field, any error is pushed in the error array
		if ( isset($_POST["user"])  &&  strlen($_POST["user"]) > 0 ) {
			$user = $_POST["user"];
		}
		else {
			array_push($errorsArray, "User field is empty");
		}
		if (
				isset($_POST["password"])  &&  strlen($_POST["password"]) > 0  &&
				isset($_POST["password2"])  &&  strlen($_POST["password2"])
			) {
			if ( $_POST["password"]  == $_POST["password2"] ) {
				$password = $_POST["password"];
				$password = md5($password);
			}
			else {
				array_push($errorsArray, "Password fields are not equal");
			}
		}
		else {
			array_push($errorsArray, "One or both password fields are empty");
		}

	// validation of errors
	// if there are some errors, alert user, and do nothing, else continue creating user
		if ( sizeof($errorsArray) > 0 ) {
			$errormessage = "";
			foreach ($errorsArray as $error) {
    			$errormessage .= $error."\\n";
			}				
?>
	<script language="JavaScript" type="text/javascript">
		alert("<?php echo $errormessage; ?>");
	</script>
<?php	
		}
		else {
			$passwordHash = calculatePasswordHash($password);
			$passwordValidation = validatePassword($password, $passwordHash);
			echo "<p> User: " . $user . "</p>";
			echo "<p> Password: " . $password . "</p>";
			echo "<p> Password Hash: " . $passwordHash . "</p>";
			echo "<p> Password Validation: " . $passwordValidation . "</p>";
			
			$queryInsert =
					"INSERT INTO " .
						"user " .
						"( `login`, `password` )" .
					"VALUES " .
						"( '".$user."', '".$passwordHash."' )" .
					"";
			$dbConn->Execute($queryInsert);
		// TODO more code to check if operation was succesful
		}
		;
	break;

	case "verifyuser":
?>
	
<?php
		;
	break;

	default:
		;
	break;
}

?>
</body>

</html>
